package view.diaLogView;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.ModifyInformationActivity;
import com.example.administrator.text.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.MyApplication;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;
import util.getInformation;
import zxing.encoding.EncodingUtils;

/**
 * Created by liuxiaobin on 2016/12/7
 * 二维码dialog
 */
public class QrcodeDialog extends Dialog{
    private Context mContext;
    private String mID,mToken,url;
    private ImageView mImageView;
    private TextView textView,TVAgain;
    private UploadDialog mUploadDialog;
    private QrcodeDialog mQrcode;
    private org.apache.log4j.Logger mLogger = org.apache.log4j.Logger.getLogger(QrcodeDialog.class);
    private HashMap<String, Object> map;
    private int mStringType,width,heighe;    //1 代码授权上网的二维码  2个人信息的二维码
    private int mNumber = 1;                //用于 检查授权的记时
    @Override public void show() {
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        super.show();
    }

    public QrcodeDialog(Context context,int type) {
        super(context, R.style.upoad_dialog);
        this.mContext = context;
        this.mStringType = type;
        mQrcode = this;
    }

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    private void init() {
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.width = mContext.getResources().getDisplayMetrics().widthPixels;
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View mView = inflater.inflate(R.layout.qrcode_dialog,null);
        setContentView(mView, params);
        mImageView = (ImageView) mView.findViewById(R.id.image_qrcode);
        textView = (TextView)mView.findViewById(R.id.text_qrcode_hint);
        TVAgain = (TextView)mView.findViewById(R.id.tv_dialog_again); //重新生成二维码
        if(mStringType == 1){
            textView.setText("请您的好友用牛郎app扫一扫，之后可授权您使用NewFi");
        }
        initData();

        mImageView.post(new Runnable() {
            @Override
            public void run() {
                width = mImageView.getWidth();   heighe = mImageView.getHeight();
            }
        });

        TVAgain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
    }

    private void initData() {
        mID = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mUseridDB, "");
        mToken = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mTokenDB, "");
        String phone = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mHUWePhone, "");
        String name = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mNICKNAME, "");
        String headUrl =(String)SharedPreferencesUtils.getParam(mContext, ModifyInformationActivity.WEHEAD,"");

        HashMap<String, Object> map = new HashMap<>();
        map.put("userid",mID);
        map.put("phone",phone);
        map.put("nickname",name);
        map.put("siteAreaid",MyApplication.getApp().getSiteAreaid());
        map.put("ip",getInformation.getNewGetInformation(mContext).getI_IP());
        map.put("mac",getInformation.getNewGetInformation(mContext).getIMAC());
        map.put("headimg",headUrl);
        LogUtil.eE("","生成二维码"+getInformation.getNewGetInformation(mContext).getI_IP());
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_createNetQr,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,mToken,mID,Url.mStirngAccredit_createNetQr,stirngSign,time);
        if(NetUtils.getInstance(mContext).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        mLogger.info("initData()--->生成二维码--fwq"+url+"stirngSign"+stringJson+"...NF_callid..."+map1.get("NF_callid"));
        GreenTreeNetworkUtil.getInstance().doPost(mContext,url,1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    mLogger.info("initData()--->onSuccess--->String"+response);
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                     if(json.getInt("code") == 1){
                         String text = json.getString("text");
                         String sessionid = json.getString("sessionid");

                         if(width == 0){width = 350;}
                         if(heighe == 0){heighe = 350;}

                         LogUtil.eE("","width   "+width+"    heighe   "+heighe);
                         LogUtil.eE("",text);
                         Bitmap bitmap = EncodingUtils.createQRCode(text,width,heighe,null);//生成二维码
                         mImageView.setImageBitmap(bitmap);
                         mNumber = 1;
                         verifyNetQr(sessionid);
                         textView.setVisibility(View.VISIBLE);
                         TVAgain.setVisibility(View.GONE);
                     }else if (json.getInt("code") == -2) {
                         CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                         crowdRetunDialog.show();
                     }else if (json.getInt("code") == -1) {
                         Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                     }else if(json.getInt("code")== 0){
                         Toast.makeText(mContext,"请检查自己是否有权限",Toast.LENGTH_SHORT).show();
                     }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                  StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
            }
        });

    }

    /**
     * 检查授权的情况
     */
    private void verifyNetQr(final String sessionid){
        if(mNumber<13){
            if(map == null){
                map = new HashMap<>();
            }
            map.put("sessionid",sessionid);
            String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
            long time = StringUtil.getStringUtilNew().getTimeCurrent();
            String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_checkNetQr,stringJson,mToken,mID,time);
            Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,mToken,mID,Url.mStirngAccredit_checkNetQr,stirngSign,time);
            LogUtil.eE("",StringUtil.getStringUtilNew().getTimeInstance());
            if(NetUtils.getInstance(mContext).getNetWorkTeyt() == 0){
                url = Url.getUrlNew().getAppIP();
            }else {
                url = MyApplication.getApp().getFWQString();
            }
            mLogger.info("verifyNetQr()--->onSuccess()--url->检查二维码的时效性--stringJson.."+stringJson+"...NF_callid..."+map1.get("NF_callid"));
            GreenTreeNetworkUtil.getInstance().doPost(mContext,Url.mAppIP,15000,map1,new RequestDataCallback() {
                @Override
                public void onSuccess(String response) {
                    try {
                        mLogger.info("verifyNetQr()--->onSuccess()--url->检查二维码的时效性--response.."+response);
                        JSONObject json = new JSONObject(response);
                        LogUtil.eE("",response);
                        if(json.getInt("code")==1){
                            mQrcode.dismiss();
                            final RetunDialog retunDialog = new RetunDialog(mContext,"",3,true);
                            retunDialog.show();
                            HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                                @Override public void run() {
                                    retunDialog.dismiss();
                                    ((Activity)mContext).finish();
                                    /*Intent intent = new Intent(HomeActivity.mAction);
                                    intent.putExtra("wifi","wifiok");
                                    mContext.sendBroadcast(intent);*/
                                }
                            },1000);
                        }else if (json.getInt("code") == -2) {
                            CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                            crowdRetunDialog.show();
                        }else {
                            Toast.makeText(mContext,"授权失败",Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Throwable error) {
                    mNumber++;
                    LogUtil.eE("",StringUtil.getStringUtilNew().getTimeInstance()+"............."+mNumber);
                    verifyNetQr(sessionid);
                }
            });

        }else {
            mImageView.setImageBitmap(null);
            textView.setVisibility(View.GONE);
            TVAgain.setVisibility(View.VISIBLE);
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        mQrcode.dismiss();
        mNumber = 13;
        return false;

    }
}
